const redis = require('redis')
const { REDIS_CONF } = require('../conf/db')

// 创建客户端
const redisClient = redis.createClient(REDIS_CONF.port, REDIS_CONF.host)
redisClient.on('error', err => {
    console.error(err)
})

function set(key, val) {
    if(typeof val === 'object') {
        val = JSON.stringify(val)
    }
    console.log('set key', key, val)
    redisClient.set(key, val, redis.print)
}

function get(key) {
    const promise = new Promise((resolve, reject) => {
        redisClient.get(key, (err, val) => {
            if (err) {
                reject(err)
                return
            }
            if(val === null) {
                resolve(null)
                return
            }
            try { // 此处不是为了抓捕异常，是为了兼容JSON字符串
                resolve(
                    JSON.parse(val)
                )
            } catch(ex) {
                resolve(val)
            }
            console.log('get ---- val:', val)
            resolve(val)
            // 退出
            // redisClient.quit()
        })
    })
    return promise
}

module.exports = {
    set, 
    get
}